﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class GameMode : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!HttpContext.Current.Request.IsAuthenticated)
        {
            Response.Redirect("~/login.aspx");
        }
        else
        {
            lblGameModeMessage.Visible = false;

            //Create sql connection string and sql commands.
            string strConnection = ConfigurationManager.ConnectionStrings["stockmarketConnectionString"].ConnectionString;
            SqlConnection sqlConnection = new SqlConnection(strConnection);

            //Get all the GameID and GameName in game table.
            string strSelect = "SELECT Game.GameID, Game.GameName + '  ('+ SimulationCategory.Category+')' AS Gametbl  FROM Game INNER JOIN SimulationCategory ON Game.CategoryID = SimulationCategory.CategoryID ORDER BY Game.GameID";

            SqlCommand cmdfindgamelist = new SqlCommand(strSelect, sqlConnection);

            //Get the Username and GameID in gameusers table.
            String strselect2 = "Select UserName, GameID from [GameUsers] where UserName ='" + User.Identity.Name + "'";
            SqlCommand findgameusr = new SqlCommand(strselect2, sqlConnection);
            DataSet dataset = new DataSet();
            SqlDataAdapter dAdapter = new SqlDataAdapter(findgameusr);
            dAdapter.Fill(dataset);

            try
            {
                //Check if user has already join a previous game.
                sqlConnection.Open();
                SqlDataReader dr = findgameusr.ExecuteReader();

                if (dr.HasRows)
                {
                    //Populate and listout all the current games in gametable.
                    dr.Close();
                    SqlDataReader reader = cmdfindgamelist.ExecuteReader();

                    Gamelist.DataSource = reader;
                    Gamelist.DataTextField = "Gametbl";
                    Gamelist.DataValueField = "GameID";
                    Gamelist.DataBind();

                   // Set the selected game in the dropdownbox when loading the page.
                   //Display appropriate buttons text and game messages.
                    Gamelist.SelectedValue = dataset.Tables[0].Rows[0]["GameID"].ToString();
                    Gamelist.Enabled = false;
                    Button1.Text = "Leave";
                    lblGameModeMessage.Visible = true;
                    lblGameModeMessage.Text = "You are currently in a game.";
                    lblGameModeMessage.ForeColor = System.Drawing.Color.Green;

                }

                else
                {
                    dr.Close();
                    //Populate and listout all the current games in gametable.
                    SqlDataReader reader = cmdfindgamelist.ExecuteReader();

                    if (!IsPostBack)
                    {

                        Gamelist.DataSource = reader;
                        Gamelist.DataTextField = "Gametbl";
                        Gamelist.DataValueField = "GameID";
                        Gamelist.DataBind();

                    }

                }

          }


            catch (Exception err)
            {
                //Display error message in loading list of games.
                lblGameModeMessage.Visible = true;
                lblGameModeMessage.Text = "Error reading list of games. ";
                lblGameModeMessage.Text += err.Message;
            }
            finally
            {
                sqlConnection.Close();
            }

        }
    }


    protected void Button1_Click(object sender, EventArgs e)
    {

        int newvalue = 0;

        //Create sql connection string and sql commands.
        string strConnection = ConfigurationManager.ConnectionStrings["stockmarketConnectionString"].ConnectionString;
        SqlConnection sqlConnection = new SqlConnection(strConnection);

        // Sql statement to Insert/Delete gameuser into gameusers table 
        String strInsertgameusr = "Insert into [GameUsers] (UserName,GameID) values ('" + User.Identity.Name + "' , '" + Gamelist.SelectedItem.Value + "')";
        String strDeletegameusr = "Delete From [GameUsers] Where UserName='" + User.Identity.Name + "'";
        String strDeleteUserTransaction = "Delete From [Transaction] Where UserName='" + User.Identity.Name + "' AND GameID ='" + Gamelist.SelectedItem.Value + "'";
        String strDeleteUserStock = "Delete From [UserCurrentStock] Where UserName='" + User.Identity.Name + "' AND GameID ='" + Gamelist.SelectedItem.Value + "'";

        // Retrieve the no of allowed users in the GameID. 
        String selectgamealloweddata = "SELECT  GameAllowedUser,GameID FROM [Game] where GameID='" + Gamelist.SelectedItem.Value + "'";
        SqlCommand cmdgameallowed = new SqlCommand(selectgamealloweddata, sqlConnection);

        try
        {

            //Convert the string to integer for the gameallowedval.
            sqlConnection.Open();
            String gameallowedval = cmdgameallowed.ExecuteScalar().ToString();
            int currentvalue = Convert.ToInt32(gameallowedval);

            // If current button text is "join" execute the steps
            if (Button1.Text.Equals("Join"))
            {
            //If the gameallowedval user is 0 , display game full msg.
                if (currentvalue == 0) 
                {
                    lblGameModeMessage.Visible = true;
                    lblGameModeMessage.Text = " This Game is full.";

                }
                
            else
                {
                
                //Decrease the gameallowed value in game table.
                newvalue = currentvalue - 1;
                string updategameallowed = "Update [Game] set Gamealloweduser =" + newvalue + " where GameID='" + Gamelist.SelectedItem.Value + "'";

                SqlCommand cmdinsertgameuser = new SqlCommand(strInsertgameusr, sqlConnection);
                SqlCommand cmdupdategameallowed = new SqlCommand(updategameallowed, sqlConnection);

                cmdinsertgameuser.ExecuteNonQuery();
                cmdupdategameallowed.ExecuteNonQuery();
                Session["GameID"] = Gamelist.SelectedItem.Value;

                //Display appropriate buttons text and game messages.
                Gamelist.Enabled = false;
                Button1.Text = "Leave";
                lblGameModeMessage.Visible = true;
                lblGameModeMessage.Text = "You have sucessfully join the game.";
                lblGameModeMessage.ForeColor = System.Drawing.Color.Green;
                }

            }

            // If current button text is "Leave" execute the steps
            else if (Button1.Text.Equals("Leave"))
            {
                //Increase the gameallowed value in game table.
                newvalue = currentvalue + 1;
                string updategameallowed = "Update [Game] set Gamealloweduser =" + newvalue + " where GameID='" + Gamelist.SelectedItem.Value + "'";

                SqlCommand cmddeletegameuser = new SqlCommand(strDeletegameusr, sqlConnection);
                SqlCommand cmdupdategameallowed = new SqlCommand(updategameallowed, sqlConnection);

                cmddeletegameuser.ExecuteNonQuery();
                cmdupdategameallowed.ExecuteNonQuery();

                cmddeletegameuser.CommandText = strDeleteUserStock;
                cmddeletegameuser.ExecuteNonQuery();

                cmddeletegameuser.CommandText = strDeleteUserTransaction;
                cmddeletegameuser.ExecuteNonQuery();

                Session["GameID"] = "-1";

                //Display appropriate buttons text and game messages.
                Gamelist.Enabled = true;
                Button1.Text = "Join";
                lblGameModeMessage.Visible = true;
                lblGameModeMessage.Text = "You have sucessfully leave the game.";
                lblGameModeMessage.ForeColor = System.Drawing.Color.Green;
            }

        }


        catch (Exception err)
        {
            //Display error messages for Joining or leaving game button.
            lblGameModeMessage.Visible = true;
            lblGameModeMessage.Text = "Error join/leave game. ";
            lblGameModeMessage.Text += err.Message;
        }

        finally
        {
            sqlConnection.Close();
        }



    }

   
}
